<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="p-2 modal_main">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small" label-width="80">
            <el-form-item label="机型名称">
              <el-select v-model="queryParams.modelNumber" clearable placeholder="请选择机型" @change="modelChange1">
                <el-option v-for="item in queryModelNumberList" :label="item.name" :value="item.mark"
                  :key="'query+' + item.mark"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="批次">
              <el-select v-if="!queryParams.modelNumber" v-model="queryParams.batchNumber" filterable clearable
                placeholder="请选择批次">
                <el-option v-for="(item, index) in queryBatchList" :label="queryBatchList[index]"
                  :value="queryBatchList[index]" :key="'query+' + index"></el-option>
              </el-select>
              <el-autocomplete v-else v-model="queryParams.batchNumber" :fetch-suggestions="querySearch1" clearable
                class="inline-input w-50" placeholder="请输入批次号" />
            </el-form-item>
            <el-form-item label="部段">
              <el-select v-model="queryParams.sectionNumber" filterable clearable placeholder="请选择部段">
                <el-option v-for="(item, index) in querySectionList" :label="item.name" :value="item.mark"
                  :key="'query+' + index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="padding-left: 80px">
              <el-button size="small" type="primary" icon="search" @click="handleQuery">查询</el-button>
              <el-button size="small" icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button size="small" v-hasPermi="['system:oss:upload']" type="primary" plain icon="Plus"
              @click="handleFile">新增模型</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-if="showTable" v-loading="loading" :data="ossList" :header-cell-class-name="handleHeaderClass"
        @selection-change="handleSelectionChange" @header-click="handleHeaderCLick">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="对象存储主键" align="center" prop="id" />
        <el-table-column label="文件名" align="left" prop="fileName" width="180" fixed="left" show-overflow-tooltip />
        <!-- <el-table-column label="机型编号" align="left" prop="modelNumber" show-overflow-tooltip /> -->
        <el-table-column label="机型名称" align="left" prop="modelName" show-overflow-tooltip />
        <!-- <el-table-column label="批次编号" align="left" prop="batchNumber" show-overflow-tooltip /> -->
        <el-table-column label="批次名称" align="left" prop="batchName" show-overflow-tooltip />
        <el-table-column label="部段编号" align="left" prop="sectionNumber" show-overflow-tooltip />
        <el-table-column label="部段名称" align="left" prop="sectionName" show-overflow-tooltip />
        <el-table-column label="OSS文件地址" align="left" prop="url" show-overflow-tooltip />
        <el-table-column label="创建时间" align="left" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上传人" align="left" prop="createBy" />
        <el-table-column label="操作" align="left" width="250" fixed="right">
          <template #default="scope">
            <el-tooltip content="预览" placement="top">
              <el-button size="small" link type="primary" icon="View" @click="handleView(scope.row)">预览</el-button>
            </el-tooltip>
            <el-tooltip content="备注" placement="top">
              <el-button size="small" v-hasPermi="['system:oss:download']" link type="primary" icon="Document"
                @click="handleDetail(scope.row)">备注</el-button>
            </el-tooltip>
            <el-tooltip content="下载" placement="top">
              <el-button size="small" v-hasPermi="['system:oss:download']" link type="primary" icon="Download"
                @click="handleDownload(scope.row)">下载</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="small" v-hasPermi="['system:oss:remove']" link type="primary" icon="Delete"
                @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagenation">
        <pagination v-show="total > 0" style="margin-top: 0;" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" :total="total" :background="false"
          layout="total, sizes, prev, pager, next, jumper" @pagination="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="780px" append-to-body>
      <el-form ref="ossFormRef" :model="form" :rules="rules" label-width="80px" size="small">
        <!-- <el-form-item label="文件名"  prop="modelName">
          <el-input placeholder="默认为上传文件的文件名" v-model="form.modelName" />
        </el-form-item> -->
        <el-form-item label="机型名称" prop="modelNumber">
          <el-select v-model="form.modelNumber" clearable placeholder="请选择机型" @change="modelChange">
            <el-option v-for="item in modelNumberList" :label="item.name" :value="item.mark"
              :key="item.mark"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="批次名称" prop="batchNumber">
          <el-select v-if="!form.modelNumber" v-model="form.batchNumber" filterable clearable placeholder="请选择批次号">
            <el-option v-for="(item, index) in batchList" :label="batchList[index]" :value="batchList[index]"
              :key="index"></el-option>
          </el-select>
          <el-autocomplete v-else v-model="form.batchNumber" :fetch-suggestions="querySearch" clearable
            class="inline-input w-50" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="部段名称" prop="sectionNumber">
          <el-radio-group v-model="form.sectionNumber">
            <el-radio v-for="item in sectionList" :label="item.mark" :key="item.mark">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" rows="2" resize="none" v-model="form.remarks" />
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload :before-upload="handleBeforeUpload" @change="handleChange" :on-remove="handleRemove"
            :file-list="fileList" :show-file-list="true" :auto-upload="false" :multiple="false" :limit="1" action="#">
            <el-button size="small" type="primary">选取文件</el-button>
            <div class="el-upload__tip">模型文件大小超过1GB,请走离线方式</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button size="small" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="detaiDialogShow" title="备注" width="500px" append-to-body>
      <div>{{ detailInfo }}</div>
    </el-dialog>
    <el-dialog v-model="iframeVisible" v-if="iframeVisible" title="三维渲染" width="100%" append-to-body
      @close="handleClose">
      <iframe ref="iframeRef" v-if="iframeVisible" :src="iframeUrl" style="width: 100%; height: 80vh; border: none"></iframe>
    </el-dialog>
  </div>
</template>

<script setup name="Oss" lang="ts">
import { listPros, delPro, downLoadFile, prosPreiewFile } from '@/api/system/oss';
import {  OssVO } from '@/api/system/oss/types';
import { getBatchNo,  getMeshModelStructureList,  } from '@/api/dataAcquisition';
import axios from 'axios';
import { getToken } from '@/utils/auth';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const ossList = ref([]);
const showTable = ref(true);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const type = ref(0);
const previewListResource = ref(true);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const fileList = ref<any[]>([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const modelNumberList = ref([]);
const queryModelNumberList = ref([]);
const submitFile = ref(null);
// 默认排序
const defaultSort = ref({ prop: 'createTime', order: 'descending' });
const iframeUrl = ref('');
const iframeVisible = ref(false);
const iframeData = ref(null);
const iframeRef = ref(null)
const ossFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();
const detaiDialogShow = ref(false);
const detailInfo = ref('');
const batchList = ref([]);
const sectionList = ref([]);
const queryBatchList = ref([]);
const querySectionList = ref([]);
const sectionMap = ref({})
const initFormData = {
  file: undefined,
  modelNumber: '',
  batchNumber: '',
  sectionNumber: '',
  remarks: '',
};
const data = reactive({
  form: { ...initFormData },
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modelNumber: '',
    batchNumber: '',
    sectionNumber: ''
  },
  rules: {
    modelNumber: [{ required: true, message: '请选择机型', trigger: 'blur' }],
    batchNumber: [{ required: true, message: '请选择批次', trigger: 'blur' }],
    sectionNumber: [{ required: true, message: '请选择部段', trigger: 'blur' }],
    file: [{ required: true, message: '上传文件不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const handleCurrentChange = (val) => {
  // queryParams.value.pageNum = val.page;
  getList();
};
// 获取机型
const getModelList = () => {
  getMeshModelStructureList({ parentId: 0, pageSize: 999 }).then(res => {
    if (res) {
      modelNumberList.value = res.rows;
      queryModelNumberList.value = res.rows;
    }
  })
}
// 获取部段
const getSectionList = (id) => {
  getMeshModelStructureList({ parentId: id, pageSize: 999, filterSection: true }).then(res => {
    if (res) {
      sectionList.value = res.rows;
      res.rows.forEach(item => {
        sectionMap.value[item.mark] = item.name;
      })
    }
  })
}
const getSectionList1 = (id) => {
  getMeshModelStructureList({ parentId: id, pageSize: 999, filterSection: true }).then(res => {
    if (res) {
      querySectionList.value = res.rows;
      res.rows.forEach(item => {
        sectionMap.value[item.mark] = item.name;
      })
    }
  })
}
// 获取批次号
const modelChange = (val) => {
  if (val) {
    form.value.batchNumber = '';
    form.value.sectionNumber = '';
    getBatchNo({ modelNumber: val }).then(res => {
      if (res) {
        batchList.value = res.data.map(name => Object.fromEntries([['value', name]]))
        console.log(batchList.value);
        console.log(queryBatchList.value);
      }
    })
    let _id = modelNumberList.value.find(item => item.mark == val)?.id;
    _id && getSectionList(_id);
  }
}
const modelChange1 = (val) => {
  if (val) {
    queryParams.value.batchNumber = '';
    queryParams.value.sectionNumber = '';
    getBatchNo({ modelNumber: val }).then(res => {
      if (res) {
        queryBatchList.value = res.data.map(name => Object.fromEntries([['value', name]]))
      }
    })
    let _id = queryModelNumberList.value.find(item => item.mark == val)?.id;
    _id && getSectionList1(_id);
  }
}
// 查看详情
const handleDetail = (data) => {
  detaiDialogShow.value = true;
  detailInfo.value = data.remarks;
};
// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
  // 校检文件大小
  const isLt = file.size / 1024 / 1024 < 1024;
  if (!isLt) {
    proxy?.$modal.msgError(`上传文件大小不能超过 1024 MB!`);
    return false;
  }
  return true;
};
const handleRemove = (file: any) => {
  fileList.value = [];
  form.value.file = null;
};
const handleChange = (file: any) => {
  submitFile.value = file;
  form.value.file = file;
  ossFormRef.value.validate();
};

/** 查询模型列表 */
const getList = async () => {
  loading.value = true;
  const res = await proxy?.getConfigKey('sys.oss.previewListResource');
  previewListResource.value = res?.data === undefined ? true : res.data === 'true';
  const response = await listPros(proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime'));
  ossList.value = response.rows;
  total.value = response.total;
  loading.value = false;
  showTable.value = true;
};
/** 取消按钮 */
function cancel() {
  dialog.visible = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = { ...initFormData };
  ossFormRef.value?.resetFields();
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  showTable.value = false;
  dateRangeCreateTime.value = ['', ''];
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    modelNumber: '',
    batchNumber: '',
    sectionNumber: ''
  };
  handleQuery();
}
/** 选择条数  */
function handleSelectionChange(selection: OssVO[]) {
  ids.value = selection.map((item) => item.modelId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 设置列的排序为我们自定义的排序 */
const handleHeaderClass = ({ column }: any): any => {
  column.order = column.multiOrder;
};
/** 点击表头进行排序 */
const handleHeaderCLick = (column: any) => {
  if (column.sortable !== 'custom') {
    return;
  }
  switch (column.multiOrder) {
    case 'descending':
      column.multiOrder = 'ascending';
      break;
    case 'ascending':
      column.multiOrder = '';
      break;
    default:
      column.multiOrder = 'descending';
      break;
  }
  handleOrderChange(column.property, column.multiOrder);
};
const handleOrderChange = (prop: string, order: string) => {
};
/** 新增模型 */
const handleFile = () => {
  reset();
  type.value = 0;
  dialog.visible = true;
  dialog.title = '新增模型';
  fileList.value = [];
  // 设置表单默认值
  if (ossList.value.length > 0) {
    form.value.modelNumber = "";
    form.value.sectionNumber = '';
    form.value.batchNumber = "";
    form.value.remarks = "";
  }
};
/** 提交按钮 */
const submitForm = async () => {
  ossFormRef.value.validate((valid: any) => {
    if (!valid) {
      return false;
    } else {
      const formData = new FormData();
      const metadata = form.value;
      delete metadata.file;
      formData.append('file', submitFile.value.raw);
      formData.append('modelNumber', metadata?.modelNumber);
      formData.append('batchNumber', metadata?.batchNumber);
      formData.append('sectionNumber', metadata?.sectionNumber);
      formData.append('remarks', metadata?.remarks);
      let VITE_APP_BASE_API = '/dev-api';
      if (import.meta.env.MODE === 'production') {
        VITE_APP_BASE_API = '/prod-api';
      }
      if (import.meta.env.MODE === 'green') {
        VITE_APP_BASE_API = '/isfd-api';
      }
      axios
        .post(`${VITE_APP_BASE_API}/isfd/preProcess/model/save`, formData, {
          headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Bearer ' + getToken() }
        })
        .then((res) => {
          dialog.visible = false;
          fileList.value = [];
          getList();
        });
    }
  });
};
/** 下载按钮操作 */
const handleDownload = (row) => {
  downLoadFile({ id: row?.id }).then(res => {
    if (res) {
      const blob = new Blob([res], { type: 'application/octet-stream' });
      const url = window.URL.createObjectURL(blob);
      console.log(url);
      const a = document.createElement('a');
      a.href = url;
      a.download = row.fileName;
      a.click();
      window.URL.revokeObjectURL(url);
    }
  })
  // const a = document.createElement('a');
  // // const url = window.URL.createObjectURL(new Blob([data], { type: type }));
  // a.href = row?.url;
  // a.download = row.fileName;
  // a.click();
  // window.URL.revokeObjectURL(row?.url);
};
/** 删除按钮操作 */
const handleDelete = async (row) => {
  const modelIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除文件名为"' + row?.fileName + '"的数据项?');
  loading.value = true;
  await delPro(modelIds).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};
const querySearch = (queryString, cb) => {
  const results = queryString
    ? batchList.value.filter(item => item.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
    : batchList.value
  cb(results)
}
const querySearch1 = (queryString, cb) => {
  const results = queryString
    ? queryBatchList.value.filter(item => item.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
    : queryBatchList.value
  cb(results)
}
const handleClose = () => {
  iframeVisible.value = false;
  iframeUrl.value = '';
  iframeData.value = null;
};
//预览
const handleView = (row) => {
  prosPreiewFile(row?.id).then(res => {
    if (res) {
      iframeUrl.value = res?.data?.renderUrl || '';
      iframeVisible.value = true;
      iframeData.value = row;
    }
  })

};
onMounted(() => {
  getList();
  getModelList();
});
</script>
<style lang="scss" scoped>
.modal_main {
  height: calc(100vh - 180px);
  overflow: auto;
}

.pagenation {
  display: flex;
  justify-content: end;
  margin-top: 10px;
}

:deep(.el-upload) {
  display: block;
}
</style>
